package com.ctshk.rpc.system.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ctshk.common.dto.Result;
import com.ctshk.common.enums.SystemError;
import com.ctshk.common.exception.BusinessException;
import com.ctshk.common.model.PageResponse;
import com.ctshk.common.utils.EntityUtil;
import com.ctshk.common.utils.SnowflakeIdWorker;
import com.ctshk.rpc.system.dto.mian.data.MainDataInternalCompanyDTO;
import com.ctshk.rpc.system.dto.mian.data.MainDataSubjectDTO;
import com.ctshk.rpc.system.entity.MainDataInternalCompany;
import com.ctshk.rpc.system.entity.MainDataSubject;
import com.ctshk.rpc.system.mapper.MainDataInternalCompanyMapper;
import com.ctshk.rpc.system.req.main.data.MainDataInternalCompanyAddReq;
import com.ctshk.rpc.system.req.main.data.MainDataInternalCompanyListReq;
import com.ctshk.rpc.system.service.IMainDataInternalCompanyService;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Objects;

/**
 * <p>
 * 主数据 - 内部公司 服务实现类
 * </p>
 *
 * @author 叶冠峰
 * @since 2021-06-22
 */
@DubboService
public class MainDataInternalCompanyServiceImpl extends ServiceImpl<MainDataInternalCompanyMapper, MainDataInternalCompany> implements IMainDataInternalCompanyService {

    @Autowired
    private MainDataInternalCompanyMapper mainDataInternalCompanyMapper;


    /**
     * 列表
     *
     * @param req
     * @return
     */
    @Override
    public PageResponse<MainDataInternalCompanyDTO> list(MainDataInternalCompanyListReq req) {
        Page<MainDataInternalCompany> iPage = new Page<>(req.getPageNo(), req.getPageSize());
        QueryWrapper<MainDataInternalCompany> queryWrapper = new QueryWrapper<>();
        if (StringUtils.isNotBlank(req.getName())){
            queryWrapper.like("cn_name",req.getName());
            queryWrapper.or();
            queryWrapper.like("en_name",req.getName());
        }
        queryWrapper.eq(req.getStatus() != null,"status",req.getStatus());
        queryWrapper.like(StringUtils.isNotBlank(req.getCompanyNumber()),"company_number",req.getCompanyNumber());
        queryWrapper.eq(req.getPaySubjectId() != null,"pay_subject_id",req.getPaySubjectId());
        queryWrapper.eq(req.getReceiveSubjectId() != null,"receive_subject_id",req.getReceiveSubjectId());
        queryWrapper.eq("is_deleted",0);
        Page<MainDataInternalCompany> page = mainDataInternalCompanyMapper.selectPage(iPage, queryWrapper);
        if (CollectionUtils.isEmpty(page.getRecords())) {
            return PageResponse.empty(page.getCurrent());
        }
        List<MainDataInternalCompanyDTO> list = EntityUtil.copyList(page.getRecords(),MainDataInternalCompanyDTO.class);
        return new PageResponse<>(list,
                page.getCurrent() == 1,
                page.getTotal() <= (page.getCurrent() * page.getSize()),
                page.getTotal(), page.getCurrent(), page.getSize());
    }

    /**
     * 新增/修改
     *
     * @param req
     * @param userId
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result add(MainDataInternalCompanyAddReq req, Long userId) {
        MainDataInternalCompany company = EntityUtil.copy(req,MainDataInternalCompany.class);
        LocalDateTime now = LocalDateTime.now();
        boolean result = false;
        if (req.getId() == null){
            //新增
            company.setId(SnowflakeIdWorker.nextId());
            company.setStatus(0);
            company.setCreateId(userId);
            company.setGmtCreate(now);
            company.setIsDeleted(0);
            result = save(company);
        }else{
            //修改
            company.setModifiedId(userId);
            company.setGmtModified(now);
            result = updateById(company);
        }
        if (!result){
            throw new BusinessException(SystemError.SYS_408);
        }
        return Result.success(company.getId());
    }

    /**
     * 详情
     *
     * @param id
     * @return
     */
    @Override
    public Result<MainDataInternalCompanyDTO> detail(Long id) {
        MainDataInternalCompany company = getById(id);
        if (company == null || Objects.equals(company.getIsDeleted(),1)){
            return Result.failed(new BusinessException(SystemError.SYS_411));
        }
        MainDataInternalCompanyDTO dto = EntityUtil.copy(company,MainDataInternalCompanyDTO.class);
        return Result.success(dto);
    }

    /**
     * 修改状态
     *
     * @param id
     * @param userId
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result status(Long id, Long userId) {
        MainDataInternalCompany company = getById(id);
        if (company == null || Objects.equals(company.getIsDeleted(),1)){
            return Result.failed(new BusinessException(SystemError.SYS_411));
        }
        int status = company.getStatus().intValue() == 1?0:1;
        company.setStatus(status);
        company.setGmtCreate(LocalDateTime.now());
        company.setModifiedId(userId);
        boolean update = updateById(company);
        if (!update){
            throw new BusinessException(SystemError.SYS_408);
        }
        return Result.success(company.getId());
    }

    /**
     * 删除
     *
     * @param id
     * @param userId
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result del(Long id, Long userId) {
        MainDataInternalCompany company = getById(id);
        if (company == null || Objects.equals(company.getIsDeleted(),1)){
            return Result.failed(new BusinessException(SystemError.SYS_411));
        }
        company.setIsDeleted(1);
        company.setGmtCreate(LocalDateTime.now());
        company.setModifiedId(userId);
        boolean update = updateById(company);
        if (!update){
            throw new BusinessException(SystemError.SYS_408);
        }
        return Result.success(company.getId());
    }
}
